import React, { useState, useEffect, useRef } from 'react';
import { Button, Modal, Spin, message, Tag, Image } from 'antd';
import { EyeOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { ProTable, ProColumns } from '@ant-design/pro-components';
import type { ActionType, ProTableProps } from '@ant-design/pro-components';
import ApiService, { Category, Product } from '../services/api';
import './products.css';

const ProductsPage: React.FC = () => {
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const actionRef = useRef<ActionType>();

  useEffect(() => {
    fetchCategories();
  }, []);

  const fetchCategories = async () => {
    try {
      setLoading(true);
      const data = await ApiService.getCategories();
      const activeCategories = data.filter(cat => cat.is_active);
      setCategories(activeCategories);
      
      // 默认选择第一个分类
      if (activeCategories.length > 0) {
        setSelectedCategory(activeCategories[0].id);
      }
    } catch (error) {
      console.error('获取分类失败:', error);
      message.error('获取分类失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCategoryChange = (categoryId: number) => {
    setSelectedCategory(categoryId);
    // 刷新表格数据
    actionRef.current?.reload();
  };

  const handleViewDetail = async (product: Product) => {
    setSelectedProduct(product);
    setDetailModalVisible(true);
    setDetailLoading(true);

    try {
      // 获取完整产品信息（包括详情和图片）
      const [productData, detailData] = await Promise.all([
        ApiService.getProduct(product.id),
        ApiService.getProductDetail(product.id)
      ]);

      setSelectedProduct({
        ...productData,
        detail: detailData
      });
    } catch (error) {
      console.error('获取产品详情失败:', error);
      message.error('获取产品详情失败');
    } finally {
      setDetailLoading(false);
    }
  };

  const columns: ProColumns<Product>[] = [
    {
      title: '商品图片',
      dataIndex: 'first_image_url',
      search: false,
      width: 120,
      render: (_, record) => (
        <div style={{ width: 80, height: 80, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {record.first_image_url ? (
            <Image
              src={`http://101.33.122.140:8000${record.first_image_url}`}
              alt={record.name}
              style={{ width: '100%', height: '100%', objectFit: 'cover' }}
              preview={false}
            />
          ) : (
            <div style={{ 
              width: '100%', 
              height: '100%', 
              background: '#f5f5f5', 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center',
              fontSize: '12px',
              color: '#999'
            }}>
              暂无图片
            </div>
          )}
        </div>
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: false,
          },
        ],
      },
    },
    {
      title: '价格',
      dataIndex: 'price',
      search: false,
      sorter: true,
      render: (_, record) => (
        <span className="current-price">¥{(record.price ?? 0).toFixed(2)}</span>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      search: false,
      ellipsis: true,
      width: 200,
    },
   
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (_, record) => [
        <Button
          key="detail"
          type="link"
          size="small"
          icon={<EyeOutlined />}
          onClick={() => handleViewDetail(record)}
        >
          详情
        </Button>,
      ],
    },
  ];

  // 定义请求数据的函数
  const request: ProTableProps<Product, any>['request'] = async (params, sort, filter) => {
    try {
      const queryParams: any = {
        skip: ((params.current || 1) - 1) * (params.pageSize || 10),
        limit: params.pageSize || 10,
      };
      console.log(params,'params');
      

      // 添加分类筛选
      if (selectedCategory) {
        queryParams.category_id = selectedCategory;
      }

      // 添加名称搜索
      if (params.name) {
        queryParams.name = params.name;
      }

      const response = await ApiService.getProducts(queryParams);
      
      return {
        data: response.items || [],
        success: true,
        total: response.total || 0,
      };
    } catch (error) {
      console.error('获取产品列表失败:', error);
      message.error('获取产品列表失败');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  if (loading) {
    return (
      <div className="loading-container">
        <Spin size="large" />
        <p>加载中...</p>
      </div>
    );
  }

  return (
    <div className="products-page">
      <div className="products-header">
        <Button 
          type="link" 
          icon={<ArrowLeftOutlined />} 
          onClick={() => window.history.back()}
          className="back-btn"
        >
          返回
        </Button>
        <h1 className="page-title">商品浏览</h1>
      </div>

      <div className="products-content">
        {/* 分类标签 */}
        <div className="category-tabs" style={{
          background: '#f8f9fa',
          padding: '16px 20px',
          borderRadius: '8px',
          marginBottom: '20px',
          border: '1px solid #e8e9ea',
          boxShadow: '0 1px 3px rgba(0,0,0,0.05)'
        }}>
          <div style={{ 
            marginBottom: '12px', 
            fontSize: '14px', 
            fontWeight: '500',
            color: '#666'
          }}>
            产品分类
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
            {categories.map(category => (
              <Tag.CheckableTag
                key={category.id}
                checked={selectedCategory === category.id}
                onChange={() => handleCategoryChange(category.id)}
                style={{ 
                  padding: '6px 12px', 
                  fontSize: '13px',
                  cursor: 'pointer',
                  borderRadius: '16px',
                  border: selectedCategory === category.id 
                    ? '1px solid #1890ff' 
                    : '1px solid #d9d9d9',
                  backgroundColor: selectedCategory === category.id 
                    ? '#e6f7ff' 
                    : '#ffffff',
                  color: selectedCategory === category.id 
                    ? '#1890ff' 
                    : '#666',
                  transition: 'all 0.2s ease',
                  fontWeight: selectedCategory === category.id ? '500' : '400'
                }}
              >
                {category.name}
              </Tag.CheckableTag>
            ))}
          </div>
        </div>

        {/* ProTable */}
        <ProTable<Product>
          className="products-table"
          columns={columns}
          actionRef={actionRef}
          request={request}
          rowKey="id"
          search={{
            labelWidth: 'auto',
            collapsed: false,
            collapseRender: false,
            searchText: '搜索',
            resetText: '重置',
          }}
          pagination={{
            defaultPageSize: 10,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
          }}
          options={{
            reload: true,
            setting: false,
            density: false,
          }}
          params={{
            category_id: selectedCategory,
          }}
        />
      </div>

      {/* 产品详情弹窗 */}
      <Modal
        title="商品详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={800}
        className="product-detail-modal"
      >
        {detailLoading ? (
          <div style={{ textAlign: 'center', padding: '40px' }}>
            <Spin size="large" />
          </div>
        ) : selectedProduct ? (
          <div className="product-detail-content">
            {/* 基本信息 */}
            <div className="product-basic-info">
              <h2>{selectedProduct.name}</h2>
              <p className="product-price">
                <span className="current-price">¥{selectedProduct.price?.toFixed(2)}</span>
              </p>
              <p className="product-description">{selectedProduct.description}</p>
            </div>
         {/* 产品规格 */}
         {selectedProduct.detail.specifications && (
                  <div className="specifications-section">
                    <h3>产品规格</h3>
                    <pre className="specifications-content">
                      {selectedProduct.detail.specifications}
                    </pre>
                  </div>
                )}

                {/* 产品特色 */}
                {selectedProduct.detail.features && (
                  <div className="features-section">
                    <h3>产品特色</h3>
                    <pre className="features-content">
                      {selectedProduct.detail.features}
                    </pre>
                  </div>
                )}
            {/* 产品图片展示 */}

                   {selectedProduct.images && selectedProduct.images.length > 0 && (
              <div className="product-images">
                <h3>产品图片</h3>
                <div className="images-grid">
                  {selectedProduct.images.map((image, index) => (
                    <Image
                      key={index}
                      src={`http://101.33.122.140:8000/api/v1/upload/images/${image.id}`}
                      alt={`${selectedProduct.name} - ${index + 1}`}
                      width={120}
                      height={120}
                      style={{ objectFit: 'cover', borderRadius: '8px' }}
                    />
                  ))}
                </div>
              </div>
            )}

            {/* 详细信息 */}
            {selectedProduct.detail && (
              <div className="product-detail-info">

                {/* 富文本内容 */}
                {selectedProduct.detail.rich_content && (
                  <div className="rich-content-section">
                    <h3>详细介绍</h3>
                    <div 
                      className="rich-content"
                      dangerouslySetInnerHTML={{ __html: selectedProduct.detail.rich_content }}
                    />
                  </div>
                )}

       
              </div>
            )}
          </div>
        ) : null}
      </Modal>
    </div>
  );
};

export default ProductsPage; 